package com.carmaintain.db;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import com.carmaintain.config.Configs;

public class DBConn
{
	private static Connection conn;
	private static String MySqldriver;	
	public static String MySqlURL;
	
	static {
		try {
			conn = getConnToMySql();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static Connection getConnToMySql() throws ClassNotFoundException, SQLException, FileNotFoundException, IOException {
		MySqldriver = "com.mysql.jdbc.Driver";
		MySqlURL = "jdbc:mysql://"; 

		if (conn != null && !conn.isClosed()) {
			return conn;
		}
		
		Properties config = new Properties();
		config.load(new FileInputStream(URLDecoder.decode(Configs.class.getResource("").getPath(), "UTF-8") + File.separator + "config.properties"));
		
		MySqlURL = MySqlURL + config.getProperty("db_server") + ":" + config.getProperty("port") + "/" + config.getProperty("db_name") + "?user="
				+ config.getProperty("user") + "&password=" + config.getProperty("password")
				+ "&useUnicode=true&characterEncoding=utf-8"+
				"&zeroDateTimeBehavior=convertToNull&zeroDateTimeBehavior=round";
		Class.forName(MySqldriver);
		conn = DriverManager.getConnection(MySqlURL);

		return conn;
	}
	
	public static ResultSet query(String sql) throws SQLException, ClassNotFoundException, FileNotFoundException, IOException {
		return getConnToMySql().createStatement().executeQuery(sql);
	}
	
	public static int update(String sql) throws SQLException, ClassNotFoundException, FileNotFoundException, IOException {
		return getConnToMySql().createStatement().executeUpdate(sql);
	}
}